import { Component, Input, OnChanges } from "@angular/core";
import * as echarts from "echarts";
import { UtilService } from "src/app/core/util/util.service";
import { StatBase } from "./stat-base";
import { PercentPipe } from "@angular/common";

@Component({
    selector: "app-statistics",
    templateUrl: "./statistics.component.html",
    styleUrls: ["./statistics.component.scss"]
})
export class StatisticsComponent extends StatBase implements OnChanges {
    @Input() statOpt: any = {};
    statType: string;
    baseList: any[] = [];

    officeOpt1: any = {
        title: {
            text: "灌溉面积(万亩)",
            x: "center",
            textStyle: {
                color: "#777",
                fontSize: 15
            }
        },
        grid: {
            top: "12%",
            left: "4%",
            right: "4%",
            bottom: "5%",
            containLabel: true
        },
        tooltip: {
            trigger: "axis",
            axisPointer: {
                type: "shadow"
            }
        },
        xAxis: {
            type: "value",
            axisLine: {
                show: false
            }
        },
        yAxis: {
            type: "category",
            data: [],
            axisLabel: {
                textStyle: {
                    fontSize: 14,
                    color: "#777"
                }
            }
        },
        series: [
            {
                type: "bar",
                data: [],
                barCategoryGap: "60%",
                itemStyle: {
                    normal: {
                        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                            { offset: 0, color: "#4889FF" },
                            { offset: 1, color: "#56C8F2" }
                        ])
                    }
                }
            }
        ]
    };
    irrData: any = {
        totalIrrArea: 0,
        lengthSum: 0,
        maxInlet: 0
    };
    irrOptChange: any = {};
    officeOptChange1: any[] = [];
    officeOptChange2: any[] = [];
    // officeOptChange2: any = {};

    stationOptChange1: any = {};
    stationOptChange2: any = {};

    ganquData: any = {
        lengthSum: 0
    };
    ganquOptChange1: any = {};
    ganquOptChange2: any = {};

    sectionData: any = {
        areaSum: 0
    };

    pumpData: any = {
        areaSum: 0
    };
    pumpFlowOptChange: any = {};
    pumpCapacityOptChange: any = {};

    dieshuiOptChange1: any = {};
    dieshuiOptChange2: any = {};

    zhihongquOptChange1: any = {};
    zhihongquOptChange2: any = {};

    qskMapper: any = {
        'db': '地表水',
        'dx': '地下水',
        'gy': '工业',
        'ny': '农业',
        'sh': '生活',
        'zlqsk': '闸',
        'qdlqsk': '渠道',
        'bzlqsk': '泵站',
        'sjlqsk': '水井',
        'blqsk': '坝',
        'sdzlqsk': '水电站',
        'qtlqsk': '其他',
    };
    dmMapper: any = {
        'hh': '黄河断面',
        'gqdm': '干渠断面',
        'shg': '山洪沟断面',
        'psg': '排水沟断面',
        'hd': '河道水文站',
        'yz': '堰闸水文站',
        'skswz': '水库水文站',
        'ylz': '雨量站',
        'sqz': '墒情站'
    };

    constructor(private util: UtilService, private percentPipe: PercentPipe) {
        super();
    }

    ngOnChanges(): void {
        console.log(this.statOpt);
        this.statType = this.statOpt.statType;
        this.baseList = this.statOpt.baseList;

        switch (this.statType) {
            case "office":
                this.renderChartOffice();
                break;
            case "station":
                this.renderChartStation();
                break;
            case "ganqu":
                this.renderChartCanal();
                break;
            case "section":
                this.renderChartSection();
                break;
            case "bengzhan":
                this.renderChartPump();
                break;
            case "dieshui":
                this.renderChartDieshui();
                break;
            case "zhihongqu":
                this.renderChartZhiHongQu();
                break;
            case "irrArea":
                this.renderChartIrr();
                break;
        }
    }

    renderChartOffice() {
        const colorList = ["#6084fd", "#8abe78", "#69c0fe"];
        let nameList = this.util.getItemValues(this.baseList, "manageName");
        nameList = nameList.map(name => {
            name = name.replace(/管理处|市水务局|扬水管理处/, "");
            return name;
        });

        const areaList = this.util.getItemValues(
            this.baseList,
            "irrigatedArea",
            true
        );
        const areaMax = this.util.max(areaList);
        const percentList = areaList.map(area => {
            return Math.floor((area * 100) / areaMax);
        });
        this.officeOptChange1 = nameList
            .reduce((def, name, i) => {
                def.push({
                    name,
                    percent: percentList[i],
                    area: areaList[i],
                    color: colorList[i % 3]
                });
                return def;
            }, [])
            .reverse();

        const capacityList = this.util.getItemValues(
            this.baseList,
            "annulWaterDiversionCapacity",
            true
        );
        const capacityMax = this.util.max(capacityList);
        const capacityPer = capacityList.map(c => {
            return Math.floor((c * 100) / capacityMax);
        });
        this.officeOptChange2 = nameList
            .reduce((def, name, i) => {
                def.push({
                    name,
                    percent: capacityPer[i],
                    area: capacityList[i],
                    color: colorList[i % 3]
                });
                return def;
            }, [])
            .reverse();

        // this.officeOptChange2 = {
        //   title: {
        //     text: "年平均引水能力"
        //   },
        //   yAxis: {
        //     name: "(亿m³)"
        //   },
        //   series: [
        //     {
        //       data: this.baseList.map((item, idx) => [
        //         idx + 1,
        //         this.util.transformValue(item.annulWaterDiversionCapacity),
        //         item.manageName
        //       ])
        //     }
        //   ]
        // };
    }

    renderChartStation() {
        const irrigatedArea = this.util.getItemValues(
            this.baseList,
            "irrigatedArea",
            true
        );
        const canalLength = this.util.getItemValues(
            this.baseList,
            "canalLength",
            true
        );
        this.stationOptChange1 = {
            title: {
                text: "灌溉面积"
            },
            xAxis: {
                data: ["最大值", "平均值", "中位值", "最小值"]
            },
            yAxis: {
                name: "面积(万亩)"
            },
            series: [
                {
                    data: [
                        this.util.max(irrigatedArea),
                        this.util.average(irrigatedArea),
                        this.util.median(irrigatedArea),
                        this.util.min(irrigatedArea)
                    ]
                }
            ]
        };
        this.stationOptChange2 = {
            title: {
                text: "渠道长度"
            },
            xAxis: {
                data: ["最大值", "平均值", "中位值", "最小值"]
            },
            yAxis: {
                name: "长度(km)"
            },
            series: [
                {
                    data: [
                        this.util.max(canalLength),
                        this.util.average(canalLength),
                        this.util.median(canalLength),
                        this.util.min(canalLength)
                    ]
                }
            ]
        };
    }

    renderChartCanal() {
        const length = this.util.getItemValues(this.baseList, "length", true);
        const irrigatedArea = this.util.getItemValues(
            this.baseList,
            "irrigatedArea",
            true
        );
        const irrSource = this.util.getItemValues(this.baseList, "irrSource");
        const areaMapper = this.util.getScatterMapper(irrigatedArea);
        const sourceMapper = this.util.getScatterMapper(irrSource);

        this.ganquData.lengthSum = this.util.sum(length);
        // console.log(sourceMapper);
        this.ganquOptChange1 = {
            title: {
                text: "灌溉面积分布"
            },
            xAxis: {
                name: "灌溉面积(万亩)"
            },
            tooltip: {
                trigger: "item",
                axisPointer: { type: "none" },
                formatter: params => {
                    return (
                        "灌溉面积: " +
                        params.value[0] +
                        "万亩<br>" +
                        "数量: " +
                        params.value[1] +
                        "个"
                    );
                }
            },
            series: this.util.getScatterData(areaMapper)
        };
        this.ganquOptChange2 = {
            title: {
                text: "引水水源分布"
            },
            xAxis: {
                data: Object.keys(sourceMapper)
            },
            yAxis: {
                name: "数量(个)",
                nameTextStyle: {
                    color: "#777",
                    fontSize: 13
                }
            },
            series: [
                {
                    data: Object.keys(sourceMapper).map(key => sourceMapper[key])
                }
            ]
        };
    }

    renderChartIrr() {
        const length = this.util.getItemValues(this.baseList, "trunkLegth", true);
        this.irrData.lengthSum = this.util.sum(length);
        this.irrData.totalIrrArea = this.util.sum(this.util.getItemValues(
            this.baseList,
            "irrigatedArea",
            true
        ));
        this.irrData.maxInlet = this.util.max(this.util.getItemValues(
            this.baseList,
            "maxWaterDiversionCapacity",
            true
        ));
        const irrigatedArea = this.util.getItemValues(
            this.baseList,
            "name"
        );
        const areaMapper = this.util.getScatterMapper(irrigatedArea);
        // console.log(sourceMapper);
        this.irrOptChange = {
            title: {
                text: "灌溉系数"
            },
            xAxis: {
                axisLabel: {
                    interval: 0,
                    formatter: (value) => {
                        return value.split("").join("\n");
                    }
                },
                data: Object.keys(areaMapper)
            },
            yAxis: {
                nameTextStyle: {
                    color: "#777",
                    fontSize: 13
                }
            },
            series: [
                {
                    // TODO: 灌溉系数接口返回暂时未定 后续再修改
                    data: this.util.getItemValues(this.baseList, "irrCoefficient", true)
                }
            ]
        };
    }

    renderChartSection() {
        const irrigatedArea = this.util.getItemValues(
            this.baseList,
            "controllingIrrigatedArea",
            true
        );
        this.sectionData.areaSum = this.util.sum(irrigatedArea);
    }

    renderChartPump() {
        const irrigatedArea = this.util.getItemValues(
            this.baseList,
            "controllingIrrigatedArea",
            true
        );
        const designMostFlux = this.util.getItemValues(
            this.baseList,
            "designMostFlux",
            true
        );
        const capacity = this.util.getItemValues(this.baseList, "capacity", true);
        const flowMapper = this.util.getScatterMapper(designMostFlux);
        const capacityMapper = this.util.getScatterMapper(capacity);

        this.pumpData.areaSum = this.util.sum(irrigatedArea);
        this.pumpFlowOptChange = {
            title: {
                text: "设计流量分布"
            },
            xAxis: {
                name: "设计流量(m³/s)"
            },
            tooltip: {
                trigger: "item",
                axisPointer: { type: "none" },
                formatter: params => {
                    return (
                        "设计流量: " +
                        params.value[0] +
                        "m³/s<br>" +
                        "数量: " +
                        params.value[1] +
                        "个"
                    );
                }
            },
            series: this.util.getScatterData(flowMapper)
        };
        this.pumpCapacityOptChange = {
            title: {
                text: "装机容量分布"
            },
            xAxis: {
                name: "装机容量(kw)"
            },
            tooltip: {
                trigger: "item",
                axisPointer: { type: "none" },
                formatter: params => {
                    return (
                        "装机容量: " +
                        params.value[0] +
                        "kw<br>" +
                        "数量: " +
                        params.value[1] +
                        "个"
                    );
                }
            },
            series: this.util.getScatterData(capacityMapper)
        };
    }

    renderChartDieshui() {
        const dropDiffer = this.util.getItemValues(
            this.baseList,
            "dropDiffer",
            true
        );
        const capacity = this.util.getItemValues(
            this.baseList,
            "actualCapacity",
            true
        );
        const dropDifferMapper = this.util.getScatterMapper(dropDiffer);
        const capacityMapper = this.util.getScatterMapper(capacity);

        this.dieshuiOptChange1 = {
            title: {
                text: "过水能力分布"
            },
            xAxis: {
                name: "过水能力(m³/s)"
            },
            tooltip: {
                trigger: "item",
                axisPointer: { type: "none" },
                formatter: params => {
                    return (
                        "过水能力: " +
                        params.value[0] +
                        "m³/s<br>" +
                        "数量: " +
                        params.value[1] +
                        "个"
                    );
                }
            },
            series: this.util.getScatterData(capacityMapper)
        };
        this.dieshuiOptChange2 = {
            title: {
                text: "跌差分布"
            },
            xAxis: {
                name: "跌差(m)"
            },
            tooltip: {
                trigger: "item",
                axisPointer: { type: "none" },
                formatter: params => {
                    return (
                        "跌差: " +
                        params.value[0] +
                        "m<br>" +
                        "数量: " +
                        params.value[1] +
                        "个"
                    );
                }
            },
            series: this.util.getScatterData(dropDifferMapper)
        };
    }

    renderChartZhiHongQu() {
        const actualStorage = this.util.getItemValues(
            this.baseList,
            "actualStorage",
            true
        );
        const actualDischarge = this.util.getItemValues(
            this.baseList,
            "actualDischarge",
            true
        );
        const actualStorageMapper = this.util.getScatterMapper(actualStorage);
        const actualDischargeMapper = this.util.getScatterMapper(actualDischarge);

        this.zhihongquOptChange2 = {
            title: {
                text: "泄洪能力分布"
            },
            xAxis: {
                name: "泄洪能力（m³/s）"
            },
            tooltip: {
                trigger: "item",
                axisPointer: { type: "none" },
                formatter: params => {
                    return (
                        "泄洪能力: " +
                        params.value[0] +
                        "m³/s<br>" +
                        "数量: " +
                        params.value[1] +
                        "个"
                    );
                }
            },
            series: this.util.getScatterData(actualDischargeMapper)
        };
        this.zhihongquOptChange1 = {
            title: {
                text: "库容分布"
            },
            xAxis: {
                name: "库容(万m³)"
            },
            tooltip: {
                trigger: "item",
                axisPointer: { type: "none" },
                formatter: params => {
                    return (
                        "库容: " +
                        params.value[0] +
                        "万m³<br>" +
                        "数量: " +
                        params.value[1] +
                        "个"
                    );
                }
            },
            series: this.util.getScatterData(actualStorageMapper)
        };
    }
}
